package main

import (
	"context"
	"github.com/docker/docker/api/types"
	"github.com/docker/docker/api/types/filters"
	"github.com/docker/docker/client"
	. "go_learn/constant"

	"fmt"
)

// 检查镜像是否存在 docker ps -qa --filter="name=cert"
func CheckImageExist(imageName string, cli *client.Client) error {

	filterArgs := filters.NewArgs()
	filterArgs.Add("reference", imageName) //image:tag

	imageOpt := types.ImageListOptions{
		All:     true,
		Filters: filterArgs,
	}
	images, err := cli.ImageList(context.Background(), imageOpt)
	if err != nil {
		return err
	}

	if len(images) == 0 {
		fmt.Printf("This node not found image %s", imageName)
		fmt.Printf("begin pull image %s", imageName)
		rc, err := cli.ImagePull(context.Background(), imageName, types.ImagePullOptions{})
		if err != nil {
			return err
		}
		for rc != nil {
			fmt.Println(rc)
		}
	}
	return nil
}

func GetDockerApiUrl(host string) string {
	return "http://" + host + DOCKER_API_PORT
}

func main() {
	url := GetDockerApiUrl("20.26.28.194")
	cli, _ := client.NewClient(url, "1.24", nil, nil)
	if err := CheckImageExist("registry.yw.zj.chinamobile.com/kubernetes/kube-ctl-cert:v1.0", cli); err != nil {
		fmt.Println(err)
	}

}
